#coding:utf8
#  
# Author: TooNTonG
# Created on 2010-9-19
#
from third import xlrd
from datetime import datetime

def _read_ceel(sheet, row, col):
    cellType = sheet.cell_type(rowx = row, colx = col)
    cellValue = sheet.cell_value (rowx = row, colx = col)
    
    if cellType == 3 :#XL_CELL_DATE
        return  '%s' % datetime(*xlrd.xldate_as_tuple(cellValue, 0))
    elif cellType == 2:# XL_CELL_NUMBER
        return '%s' % cellValue
    elif cellType == 4: # XL_CELL_BOOLEAN:
        return 'true' if cellValue else 'false'
    elif cellType == 2 or cellType == 1:#XL_CELL_TEXT
        return cellValue.encode('utf8')
    else:
        return ''
    
def read(file_contents, sheet_index = 0):
    '''
    agrs:
        xls文件的二进制内容.只读表1
    return:
        [
            [string11, string12, string13...],
            [string21, string22, string23...],
        ....
        ]
    '''
    book = xlrd.open_workbook(file_contents = file_contents)
#    print "The number of worksheets is", book.nsheets
#    print "Worksheet name(s):", book.sheet_names()
#    print sh.name, sh.nrows, sh.ncols
    sh = book.sheet_by_index(sheet_index)
    result = []
    for rx in range(sh.nrows):
        rows = []
        for cx in range(sh.ncols):
            rows.append(_read_ceel(sh, rx, cx))
        result.append(rows)
    return result

if __name__ == '__main__':
    file_contents = open('test.et','rb').read()
    print read(file_contents)

